import { pk } from './config'
import { JSEncrypt } from 'jsencrypt'
import { decrypt } from '@js/jsencrypt'
import dayjs from 'dayjs'
import _ from 'lodash'
import qs from 'query-string'

export async function awaitWrap (promise) {
  return await promise
    .then((data) => [null, data])
    .catch(err => [err, null])
}

// 获取文件地址
export function getObjectURL (file) {
  let url = ''
  // 兼容处理
  if (window.URL.createObjectURL !== undefined) { // basic
    url = window.URL.createObjectURL(file)
  } else if (window.URL !== undefined) { // mozilla
    url = window.URL.createObjectURL(file)
  } else if (window.webkitURL !== undefined) { // webkit
    url = window.webkitURL.createObjectURL(file)
  }
  return url
}



// 公钥加密
export function compress (v) {
  // const key = new NodeRSA(pk, undefined, { encryptionScheme: 'pkcs1' })
  // const str = key.encrypt(v, 'base64')
  try {
    const encryptTool = new JSEncrypt()
    encryptTool.setPublicKey(pk)
    const str = encryptTool.encrypt(v)
    if (typeof str === 'string') {
      return str
    }
  } catch (e) {
    console.error(e)
  }
  return ''
}

// 公钥解密
export function decompress (v) {
  try {
    const str = decrypt(v, pk)
    if (typeof str === 'string') {
      return str
    }
  } catch (e) {
    console.error(e)
  }
  return ''
}

export function compressLicenseAndMobile (o) {
  if (typeof o.license === 'string' && o.license.length > 0) {
    o.license = compress(o.license)
  }
  if (typeof o.mobile === 'string' && o.mobile.length > 0) {
    o.mobile = compress(o.mobile)
  }
}

export function decompressLicenseAndMobile (o) {
  if (typeof o.license === 'string' && o.license.length > 0) {
    o.license = decompress(o.license)
  }
  if (typeof o.mobile === 'string' && o.mobile.length > 0) {
    o.mobile = decompress(o.mobile)
  }
}

// 格式化案件件证件号
export function formatCaseDataLicenseAndMobile (d) {
  const keys = ['applicant_agents', 'applicants', 'respondents', 'respondents_agents']
  keys.forEach(key => {
    const arr = d[key]
    if (arr instanceof Array && arr.length > 0) {
      arr.forEach(li => {
        if (typeof li.license === 'string' && li.license.length > 0) {
          try {
            li.license = decompress(li.license)
          } catch (e) {
            console.error(e)
          }
        }
        if (typeof li.mobile === 'string' && li.mobile.length > 0) {
          try {
            li.mobile = decompress(li.mobile)
          } catch (e) {
            console.error(e)
          }
        }
      })
    }
  })
  return d
}

// 格式化日期
export function formatDate (t, format = 'YYYY-MM-DD HH:mm', hasEmpty = true) {
  if (typeof t === 'number') {
    return dayjs(t * 1000).format(format)
  }
  if (typeof t === 'string') {
    return dayjs(t).format(format)
  }
  if (hasEmpty) {
    return '无'
  }
  return undefined
}

// 格式化金钱
export function formatMoney(money, unit = '元') {
  if (money === null) {
    return '0'
  }
  const m = String(money)
  if (!/^\d*(\.)?\d*$/.test(m)) {
    return m
  }
  return `${m.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} ${unit}`
}

export function filterRepeat (arr) {
  const s = new Set(arr)
  return [...s]
}

// 仲裁请求文本分项
export function splitItem (text) {
  text = text.trim()
  const cnNum = '一二三四五六七八九十' // 中文数字
  const pre = '\\u4e00-\\u9fa5a-zA-Z#\\-：:\'"‘’“”' // 序号前不能接的字符
  const numPre = `${pre}\\d\\.` // 阿拉伯数字序号前不能接的字符
  const split = '、,\\.，．' // 序号后的分隔符
  let nReplace = '$2$3$4$5$6$7\n'
  // 综合判断中文和阿拉伯数字序号
  let r = `(^[${cnNum}\\d][${split}]|(?=[^${numPre}]\\d{3}[${split}])(.)....|(?=[^${numPre}]\\d{2}[${split}])(.)...|(?=[^${numPre}]\\d[${split}])(.)..|(?=[^${pre}][${cnNum}]{3}[${split}])(.)....|(?=[^${pre}][${cnNum}]{2}[${split}])(.)...|(?=[^${pre}][${cnNum}][${split}])(.)..)(?![${cnNum}\\d]+)`
  if (cnNum.includes(text[0])) { // 起始为中文序号时，只判断中文序号
    r = `(^[${cnNum}][${split}]|(?=[^${pre}][${cnNum}]{3}[${split}])(.)....|(?=[^${pre}][${cnNum}]{2}[${split}])(.)...|(?=[^${pre}][${cnNum}][${split}])(.)..)`
    nReplace = '$2$3$4\n'
  } else if (/\d/.test(text[0])) { // 起始为阿拉伯数字序号时，只判断阿拉伯数字序号
    r = `(^\\d[${split}]|(?=[^${numPre}]\\d{3}[${split}])(.)....|(?=[^${numPre}]\\d{2}[${split}])(.)...|(?=[^${numPre}]\\d[${split}])(.)..)(?!\\d+)`
    nReplace = '$2$3$4\n'
  }
  const reg = new RegExp(r, 'gim')
  // const nRef = new RegExp(`(\\r\\n?|\\n)(?![${cnNum}]+[${split}])`, 'g')
  let result = text.replace(reg, nReplace).split('\n').map(li => li.trim()).filter(li => li)
  result = _.uniqWith(result, _.isEqual)
  return result
}

// 判断是否未空文本
export function filterEmptyText (v, unit = '无') {
  return v === undefined || v === '' || v === null ? unit : v
}

// 是否为null、undefind或者空字符串
export function isEmptyString (v) {
  return v === '' || v === null || v === undefined
}

// 获取搜索
export function getSearch () {
  return qs.parse(window.location.search)
}

// 限制字符串长度
export function limitStr (str, limit = 50) {
  if (typeof str === 'string' && str.length > limit) {
    return str.slice(0, limit) + '...'
  }
  return str
}

// 将字符串数字转为数字类型
export function strToNum (v) {
  if (typeof v === 'number') {
    return v
  } else if (typeof v === 'string' && !isNaN(Number(v))) {
    return Number(v)
  }
  return 0
}
